<template>
    <div class="add-page">
        <el-form ref="formRef" :model="admin" label-width="auto" label-position="right">
            <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item label="管理员名称" prop="name" :rules="[{required: true, message: '请输入管理员名称', trigger: 'blur'}]">
                        <el-input v-model="admin.name" placeholder="请输入管理员名称"/>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item label="密码" prop="pwd" :rules="[{required: true, message: '请输入密码', trigger: 'blur'}]">
                        <el-input v-model="admin.pwd" placeholder="请输入密码" type="password"/>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item label="真实姓名" prop="realname" :rules="[{required: true, message: '请输入真实姓名', trigger: 'blur'}]">
                        <el-input v-model="admin.realname" placeholder="请输入真实姓名"/>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="24">
                    <el-button type="primary" @click="doSave">保存</el-button>
                    <el-button type="default" @click="closeDialog">取消</el-button>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>

<script setup lang="ts">
import {ref} from 'vue';
import {ElMessage, FormInstance} from 'element-plus'
import axios from 'axios';

const formRef = ref<FormInstance>();
// 表单数据
const admin = ref({
    name: '',
    pwd: '',
    realname: ''
})

// 保存
const doSave = async () => {
    // 表单验证
    formRef.value?.validate(async (valid) => {
        if (valid) {
            // 验证通过，提交表单
            const { data } = await axios.post('/api/admin/register', admin.value);
            if (data.success) {
                ElMessage.success('新增成功');
                // 触发父组件的刷新页面方法。
                emits('flushPage');
                // 关闭对话框
                emits('closeDialog');
            } else {
                ElMessage.error(data.message || '新增失败');
            }
        }
    })
}

// 取消
const closeDialog = () => {
    emits('closeDialog');
}

// 定义组件的输出事件
const emits = defineEmits(['flushPage', 'closeDialog']);
</script>

<style scoped>
.add-page {
    padding: 20px;
}
</style>